﻿using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Web;

namespace Translationassistant
{
    internal class BaiDu
    {
        public string Get(string str)
        {
            try
            {
                Root root = GetTranslationFromBaiduFanyi(str, "en");

                return root.trans_result![0].dst!;
            }
            catch (Exception)
            {
                return "Error";
            }

        }

        public class Trans_resultItem
        {
            /// <summary>
            /// 你好
            /// </summary>
            public string? src { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string? dst { get; set; }
        }

        public class Root
        {
            /// <summary>
            /// 
            /// </summary>
            public string? @from { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string? to { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<Trans_resultItem>? trans_result { get; set; }
        }

        //对字符串做md5加密
        private string? GetMD5WithString(string input)
        {
            if (input == null)
            {
                return null;
            }
            MD5 md5Hash = MD5.Create();
            //将输入字符串转换为字节数组并计算哈希数据  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            //创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();
            //循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            //返回十六进制字符串  
            return sBuilder.ToString();
        }

        public enum Language
        {
            //百度翻译API官网提供了多种语言，这里只列了几种
            auto = 0,
            zh = 1,
            en = 2,
            cht = 3,
        }

        /// <summary>
        /// 中译英 
        /// </summary>
        /// <param name="q"></param>
        /// <param name="to">"en"</param>
        /// <returns></returns>
        public Root GetTranslationFromBaiduFanyi(string q, string to)
        {
            //可以直接到百度翻译API的官网申请
            //此处的都是子丰随便写的，所以肯定是不能用的
            //一定要去申请，不然程序的翻译功能不能使用
            string appId = "20191119000358717";
            string password = "6e5q7wHrKQ0llzcTZlOr";

            string jsonResult = String.Empty;

            //目标语言
            string languageTo = to.ToString().ToLower();
            //随机数
            string randomNum = System.DateTime.Now.Millisecond.ToString();
            //md5加密
            string md5Sign = GetMD5WithString(appId + q + randomNum + password)!;
            //url
            string url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from=auto&to={1}&appid={2}&salt={3}&sign={4}",
                HttpUtility.UrlEncode(q, Encoding.UTF8),
                languageTo,
                appId,
                randomNum,
                md5Sign
                );
            
            //解析json            
            Root result = JsonSerializer.Deserialize<Root>(HttpGet(url)!)!;

            return result;
        }

        /// <summary>
        /// 数据获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            try
            {
                var client = new HttpClient();
                var response = client.GetAsync(new Uri(url)).Result;
                string t = response.Content.ReadAsStringAsync().Result;
                return t;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
